<template>
  <view class="index">
    <template v-if="!getIslogin">
      <view>
        <notLogin />
      </view>
    </template>
    <template v-else>
      <view class="top-menu-view">
        <view
          class="menu-topic-view"
          v-for="item in tabs"
          :id="'tabNum' + item.id"
          :key="item.id"
        >
          <view
            @click="swichMenu(item.id)"
            :class="currentTab == item.id ? 'menu-topic-act' : 'menu-topic'"
          >
            <text class="menu-topic-text">{{ item.name }}</text>
            <view class="menu-topic-bottom">
              <view class="menu-topic-bottom-color"></view>
            </view>
          </view>
        </view>
      </view>
      <view class="content">
        <view class="competion" v-show="tabCurrent == 'tabNum0' ? true : false">
          <uni-forms
            :model="form"
            label-position="left"
            ref="form"
            :rules="rules"
          >
            <view class="header">
              <view class="body">
                <uni-forms-item label="项目" name="project_id">
                  <uni-data-picker
                    :disabled="isClock"
                    class="w100"
                    placeholder="请选择项目"
                    popup-title="请选择项目"
                    :localdata="dataTree"
                    v-model="form.project_id"
                    @change="onProjectchange"
                  ></uni-data-picker>
                </uni-forms-item>
                <uni-forms-item label="类型" name="type">
                  <uni-data-picker
                    class="w100"
                    placeholder="请选择类型"
                    popup-title="请选择类型"
                    :localdata="typeTree"
                    v-model="form.type"
                    @change="onTypeChange"
                  ></uni-data-picker>
                </uni-forms-item>
                <uni-forms-item label="工时" name="days">
                  <uni-easyinput
                    :disabled="
                      Number(form.square_meter.length) !== 0 ? true : false
                    "
                    type="digit"
                    v-model="form.days"
                    placeholder="请输入工时"
                  />
                </uni-forms-item>
                <uni-forms-item label="平方米" name="square_meter">
                  <uni-easyinput
                    :disabled="Number(form.days.length) !== 0 ? true : false"
                    type="digit"
                    v-model="form.square_meter"
                    placeholder="请输入平方米"
                  />
                </uni-forms-item>
              </view>
            </view>
            <view class="middle">
              <view class="box">
                <view class="left">
                  <view class="top">今日打卡</view>
                  <view class="bottom">
                    <template v-if="!isClock">
                      <view class="red">
                        <uni-icons
                          type="checkmarkempty"
                          color="#e06c75"
                          size="20"
                        ></uni-icons>
                        未打卡
                      </view>
                    </template>
                    <template v-else>
                      <view>
                        <uni-icons
                          type="checkmarkempty"
                          color="#0089ff"
                          size="20"
                        ></uni-icons>
                        {{ prevClockTime }}已打卡
                      </view>
                    </template>
                  </view>
                </view>
                <view class="right" v-if="date.length > 0">
                  {{ date }}
                </view>
              </view>
            </view>
            <view class="clock">
              <view class="mainBody">
                <view class="circel" @click="goClock">
                  <view class="box">
                    {{ isClock ? "已打卡" : "立即打卡" }}
                  </view>
                </view>
                <view class="address" v-if="address.length > 0">
                  <uni-icons
                    type="location"
                    color="#0d7ff0"
                    size="20"
                  ></uni-icons>
                  {{ address }}
                </view>
              </view>
            </view>
          </uni-forms>
        </view>
        <view class="xiangmu" v-show="tabCurrent == 'tabNum1' ? true : false">
          <uni-forms
            :model="adminform"
            label-position="left"
            ref="adminform"
            :rules="adminrules"
          >
            <view class="header">
              <view class="body">
                <uni-forms-item label="项目" name="project_id">
                  <uni-data-picker
                    class="w100"
                    placeholder="请选择项目"
                    popup-title="请选择项目"
                    :localdata="dataTree"
                    v-model="adminform.project_id"
                    @change="onadminProjectchange"
                  ></uni-data-picker>
                </uni-forms-item>
                <uni-forms-item label="拍照签到">
                  <uni-file-picker
                    ref="file"
                    v-model="adminimage"
                    fileMediatype="image"
                    mode="grid"
                    @select="adminselect"
                    @success="adminsuccess"
                    @fail="adminfail"
                    limit="1"
                  />
                </uni-forms-item>
              </view>
            </view>

            <view class="clock">
              <view class="mainBody">
                <view class="circel" @click="goPhoto">
                  <view class="box">
                    <view>{{ prevPhotoTime }}</view>
                    <view>{{ issign ? "已签到" : "未签到" }}</view>
                  </view>
                </view>
              </view>
            </view>
          </uni-forms>
        </view>
      </view>
    </template>
  </view>
</template>

<script>
import notLogin from "@/components/notLogin/index.vue";
import store from "@/store/index.js";
import timerSvg from "@/components/common/time.vue";
import { mapGetters } from "vuex";
import avatar from "../../components/common/avatar/index.vue";
export default {
  data() {
    return {
      setTime: null,
      date: "",
      isClock: false,
      issign: false,
      prevClockTime: "",
      address: "",
      adminimage: [],
      adminValue: [],
      tabs: [
        {
          id: 0,
          name: "打卡",
        },
      ],
      rules: {
        type: {
          rules: [
            {
              required: true,
              errorMessage: "请输入",
            },
          ],
        },
        project_id: {
          rules: [
            {
              required: true,
              errorMessage: "请输入",
            },
          ],
        },
      },
      adminrules: {
        project_id: {
          rules: [
            {
              required: true,
              errorMessage: "请输入",
            },
          ],
        },
      },
      typeTree: [],
      dataTree: [],
      isLoading: false,
      adminform: {
        place: "",
        project_id: "",
        image: "",
      },
      form: {
        location: "",
        type: "",
        project_id: "",
        days: "",
        square_meter: "",
      },
      file: null,
      imageValue: [],
      pathValue: [],
      currentTab: 0,
      tabCurrent: "tabNum0",
      prevPhotoTime: "",
    };
  },
  components: {
    avatar,
    timerSvg,
    notLogin,
  },
  computed: {
    ...mapGetters([
      "getIslogin",
      "getUserInfoName",
      "getUserInfoUserName",
      "getUserType",
    ]),
  },
  methods: {
    async adminupload() {
      try {
        const location = await this.getLocation();
        console.log(location, 205);
        if (!location) {
          return this.$errMessageToast("请选择位置在提交");
        }
        uni.showLoading({
          title: "正在上传...",
        });

        const path = this.adminValue[0];
        console.log(path, 214);
        const imgUrl = await this.uploadfile(path);
        console.log(imgUrl, 215);
        if (imgUrl) {
          this.adminform.place = location;
          this.adminform.image = imgUrl;
          const data = {
            ...this.adminform,
          };
          const result = await this.$request.request({
            url: this.$api.takePicture,
            data: JSON.stringify(data),
            header: this.$aplsjsonheader,
            isToast: true,
          });
          const currentPhotoDate = new Date();
          this.$saveStorage("photoTime", currentPhotoDate);
          this.prevPhotoTime = this.formatTimeToHHMM(currentPhotoDate);
          this.issign = true;
          uni.hideLoading();
          this.resetAdminPhoto();
        } else {
          uni.hideLoading();
          return this.$errMessageToast("获取图片错误");
        }
      } catch (e) {
        this.issign = this.issign ? false : false;
        this.$errMessageToast(e);
        console.log(e);
        //TODO handle the exception
      }
    },
    resetAdminPhoto() {
      this.adminimage = [];
      this.adminValue = [];
      this.adminform = {
        place: "",
        project_id: "",
        image: "",
      };
    },
    goPhoto() {
      this.$refs.adminform
        .validate()
        .then(async (res) => {
          try {
            if (this.vaildadminType()) {
              this.adminupload();
            }
          } catch (e) {
            this.$errMessageToast(e.message || e);
            //TODO handle the exception
          }
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    swichMenu(id) {
      this.currentTab = id;
      this.tabCurrent = "tabNum" + id;
    },
    adminselect(e) {
      const tempFiles = e.tempFiles;
      console.log(tempFiles, 224);
      for (let i = 0; i < tempFiles.length; i++) {
        this.adminValue.push({
          path: e.tempFiles[i].path,
        });
      }
    },
    adminsuccess() {},
    adminfail(e) {
      this.$errMessageToast(e.errMsg || e);
    },
    fail(e) {
      this.$errMessageToast(e.errMsg || e);
    },
    select(e) {
      const tempFiles = e.tempFiles;
      for (let i = 0; i < tempFiles.length; i++) {
        this.pathValue.push({
          path: e.tempFiles[i].path,
        });
      }
    },
    getLocation() {
      return new Promise((resolve, reject) => {
        uni.chooseLocation({
          success: function (res) {
            const location = res.name + res.address;
            if (location != "" && location.length > 0) {
              resolve(location);
            } else {
              resolve("");
            }
          },
          fail: function (e) {
            console.log("fail");
            resolve("");
            this.$errMessageToast(e | e.message | "请求地理位置出错");
          },
        });
      });
    },
    async getProjects() {
      const res = await this.$request.request({
        url: this.$api.getProject,
        method: "GET",
        isNotLoading: true,
      });
      this.dataTree = this.getValue(res);
    },
    getValue(data) {
      const arr = [...data];
      const list = arr.map((i) => {
        return {
          text: i.name,
          value: i.id,
        };
      });
      return list;
    },
    getType(data) {
      const arr = [...data];
      const list = arr.map((i) => {
        return {
          text: i.name,
          value: i.name,
        };
      });
      return list;
    },
    vaildadminType() {
      if (this.adminValue.length == 0 || this.adminValue.length == undefined) {
        throw new Error("请上传文件");
      }

      return true;
    },
    vaildType() {
      if (!this.form.days && !this.form.square_meter) {
        throw new Error("请输入工时或者平方米任意之一");
      }
      return true;
    },
    uploadfile(path) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: "http://139.199.173.67" + this.$api.uploadFile, //仅为示例，非真实的接口地址
          filePath: path.path,
          name: "file",
          header: this.$aplsFormDataheader,
          success: (res) => {
            const result = JSON.parse(res.data);
            console.log(result, 57);
            if (result.status != 200) {
              reject("上传出错了");
              return;
            }
            const imgUrl = result.data;
            if (!imgUrl) {
              reject("");
              return;
            }
            resolve(imgUrl);
          },
          fail: (eee) => {
            console.log(eee);
            reject("上传失败");
          },
        });
      });
    },
    async getTypes() {
      const res = await this.$request.request({
        url: this.$api.getType,
        method: "GET",
        isNotLoading: true,
      });
      this.typeTree = this.getType(res);
    },
    onProjectchange(e) {
      this.form.project_id = e.detail.value[0].value;
    },
    onadminProjectchange(e) {
      this.adminform.project_id = e.detail.value[0].value;
    },
    onTypeChange(e) {
      this.form.type = e.detail.value[0].value;
    },
    async upload() {
      try {
        const location = await this.getLocation();
        if (!location) {
          return this.$errMessageToast("请选择位置在提交");
        }
        uni.showLoading({
          title: "正在上传...",
        });
        this.form.location = location;
        this.address = location;
        this.isLoading = true;
        const data = {
          ...this.form,
        };
        if (!data.square_meter && data.square_meter !== 0) {
          delete data.square_meter;
        }
        if (!data.days && data.days !== 0) {
          delete data.days;
        }

        const result = await this.$request.request({
          url: this.$api.wokerSignIn,
          data: JSON.stringify(data),
          header: this.$aplsjsonheader,
          isToast: true,
        });
        const currentDate = new Date(this.date);
        this.$saveStorage("clockTime", currentDate);
        this.prevClockTime = this.formatTimeToHHMM(currentDate);
        this.isClock = true;
        uni.hideLoading();
        this.resetWorker();
      } catch (e) {
        this.isClock = this.isClock ? false : false;
        console.log(e);
        //TODO handle the exception
      }
    },
    resetWorker() {
      this.form = {
        location: "",
        type: "",
        project_id: "",
        days: "",
        square_meter: "",
      };
    },
    formatTimeToHHMM(date) {
      const hours = date.getHours().toString().padStart(2, "0"); // 小时
      const minutes = date.getMinutes().toString().padStart(2, "0"); // 分钟
      return `${hours}:${minutes}`;
    },
    getTodayTimestamp() {
      const now = new Date();
      now.setHours(0, 0, 0, 0); // 设置时间为 00:00:00
      return now.getTime();
    },
    isTimestampToday(timestamp) {
      const todayTimestamp = this.getTodayTimestamp();
      return (
        timestamp >= todayTimestamp &&
        timestamp < todayTimestamp + 24 * 60 * 60 * 1000
      );
    },
    getIsPhotoToday() {
      uni.getStorage({
        key: "photoTime",
        success: async (res) => {
          if (res.data == "" || res.data == undefined || !res.data) return;
          console.log(res.data);
          const time = res.data;
          if (this.isTimestampToday(time)) {
            console.log("时间戳代表今天");
            this.issign = true;
            this.prevPhotoTime = this.formatTimeToHHMM(time);
          } else {
            console.log("时间戳不是今天");
            this.issign = false;
          }
        },
      });
    },
    getIsClockToday() {
      uni.getStorage({
        key: "clockTime",
        success: async (res) => {
          if (res.data == "" || res.data == undefined || !res.data) return;
          console.log(res.data);
          const time = res.data;
          if (this.isTimestampToday(time)) {
            console.log("时间戳代表今天");
            this.isClock = true;
            this.prevClockTime = this.formatTimeToHHMM(time);
          } else {
            console.log("时间戳不是今天");
            this.isClock = false;
          }
        },
      });
    },
    async goClock() {
      this.$refs.form
        .validate()
        .then(async (res) => {
          try {
            if (this.vaildType()) {
              this.upload();
            }
          } catch (e) {
            this.$errMessageToast(e.message || e);
            //TODO handle the exception
          }
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    setTimer() {
      if (this.setTime) {
        clearInterval(this.setTime);
      }
      this.setTime = setInterval(() => {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        month >= 9 ? month : (month = "0" + month);
        let day = date.getDate();
        day >= 9 ? day : (day = "0" + day);
        let hour = date.getHours();
        hour >= 9 ? hour : (hour = "0" + hour);
        let minute = date.getMinutes();
        minute >= 9 ? minute : (minute = "0" + minute);
        let second = date.getSeconds();
        second >= 9 ? second : (second = "0" + second);
        this.date =
          year +
          "-" +
          month +
          "-" +
          day +
          "  " +
          hour +
          ":" +
          minute +
          ":" +
          second;
      }, 1000);
    },
  },
  created() {
    this.getProjects();
    this.getTypes();
    this.getIsClockToday();
    this.getIsPhotoToday();
  },
  mounted() {
    if (this.getUserType === "admin") {
      this.tabs.push({
        id: 1,
        name: "拍照审核",
      });
    }
  },
  onShow() {
    this.getIsClockToday();
    this.getIsPhotoToday();
    this.setTimer();
  },
  onHide() {
    clearInterval(this.setTime);
  },
};
</script>

<style scoped lang="less">
.index {
  width: 100%;
  height: 100vh;
  background-color: #eff4f6;
  display: flex;
  flex-direction: column;
  overflow: scroll;

  .xiangmu {
    .box {
      flex-direction: column-reverse;
    }
  }

  .top-menu-view {
    display: flex;
    white-space: nowrap;
    width: 100%;
    background-color: #ffffff;
    height: 86rpx;
    line-height: 86rpx;

    .menu-topic-view {
      display: inline-block;
      white-space: nowrap;
      height: 86rpx;
      position: relative;
      width: 50%;

      .menu-topic-text {
        font-size: 30rpx;
        color: #303133;
        padding: 10rpx 40rpx;
        text-align: center;
        display: block;
      }

      .menu-topic-bottom {
        position: absolute;
        bottom: 0;
        width: 100%;

        .menu-topic-bottom-color {
          width: 40rpx;
          height: 4rpx;
        }
      }

      .menu-topic-act .menu-topic-bottom {
        display: flex;
        justify-content: center;
      }

      .menu-topic-act .menu-topic-bottom-color {
        background: #3d7eff;
      }
    }
  }

  .red {
    color: orangered;
  }

  .header {
    padding: 20rpx 30rpx;
    height: auto;

    .body {
      background-color: #fff;
      border-radius: 15rpx;
      padding: 15rpx;
    }

    .box {
      background-color: #fff;
      border-radius: 15rpx;
      display: flex;
      align-items: center;
      padding: 15rpx;

      .ml {
        margin-left: 25rpx;
      }
    }
  }

  .middle {
    padding: 5rpx 30rpx;
    overflow: hidden;
    height: 200rpx;

    .box {
      background-color: #fff;
      display: flex;
      padding: 15rpx;
      align-items: center;
      border-radius: 15rpx;
      min-height: 100rpx;

      .left {
        flex: 1 0 0;
        letter-spacing: 2rpx;
        border-right: 1px solid #ccc;

        .top {
          font-weight: 700;
          font-size: 35rpx;
          margin: 10rpx;
        }

        .bottom {
          font-weight: 500;
          font-size: 30rpx;
          margin: 10rpx;
          color: #1c1956;
        }
      }

      .right {
        padding-left: 10rpx;

        flex: 2 0 0;
        font-size: 30rpx;
        color: #574558;
        font-weight: 500;
        letter-spacing: 2rpx;

        height: 100%;

        .svg {
          width: 50rpx;
          height: 50rpx;
        }
      }
    }
  }

  .clock {
    padding: 5rpx 30rpx;
    flex: 1;
    overflow: hidden;

    .mainBody {
      padding: 15rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #fff;
      height: 100%;
      display: flex;
      flex-direction: column;

      .location {
        display: flex;
        justify-content: center;
        margin-top: 30rpx;
      }

      .circel {
        width: 200rpx;
        height: 200rpx;
        border-radius: 50%;
        overflow: hidden;
        background-color: #fff;
        border: 5px solid #f3711d;

        .box {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          font-size: 40rpx;
        }
      }
    }
  }
}
</style>
